package com.wisco.web.demo.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wisco.web.demo.dao.UserDAO;
import com.wisco.web.demo.model.User;
import com.wisco.web.demo.service.UserService;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements UserService {

	@Resource
	public UserDAO userDao;
	
	public void setUserDao(UserDAO userDao){
		this.userDao = userDao;
	}
	
	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void createUser(User user) {
		userDao.insert(user);
		//UserDAO userDAO = (UserDAO) context.getBean("userDAO");
		//userDao.insert(user);

	}

	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void deleteUser(long userId) {
		//UserDAO userDAO = (UserDAO) context.getBean("userDAO");
		//userDAO.delete(userId);
		//userDAO.dd("from User");
	}

	@Override
	public List<User> searchAllUser() {
		//UserDAO userDAO = (UserDAO) context.getBean("userDAO");
		return userDao.findAll(User.class);
	}

	@SuppressWarnings("rawtypes")
	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public User loginUser(String username, String password) {

		List find = userDao.find(" from User where username=? and password=?",username, password);
		if(find!=null && find.size()==1){
			return (User)find.get(0);
		}
		return null;

	}
	
	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void insertUsers(User[] users) {
		for (int i = 0; i < users.length; i++) {
			userDao.insert(users[i]);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public String findPwd(String username, String phone) {
		List find = userDao.find(" from User where username=? and phone=?",username, phone);
		if(find!=null && find.size()==1){
			return ((User)find.get(0)).getPassword();
		}
		return null;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void completeinfo(User users) {
		userDao.saveOrUpdate(users);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public User findinformation(long userid) {
		@SuppressWarnings("unchecked")
		List<User> find = userDao.find(" from User where userid=?",userid);
		if(find!=null && find.size()==1){
			return ((User)find.get(0));
		}
		return null;
	} 
}
